package com.kehongborui.portal.service.impl;

import com.kehongborui.data.domain.AssetClassify;
import com.kehongborui.data.repository.AssetClassifyRepository;
import com.kehongborui.portal.exception.SczcException;
import com.kehongborui.portal.model.AssetClassifyModel;
import com.kehongborui.portal.service.AssetClassifyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static com.kehongborui.portal.enums.Error.ASSET_CLASSIFY_IS_EXISTS;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-09-26
 */
@Service
public class AssetClassifyServiceImpl implements AssetClassifyService {
    @Autowired
    private AssetClassifyRepository assetClassifyRepository;

    @Override
    public AssetClassifyModel save(AssetClassifyModel model) {
        AssetClassify assetClassify = new AssetClassify();
        BeanUtils.copyProperties(model, assetClassify);

        // 根据分类名称查询分类是否已经存在
        AssetClassify retAssetClassify = assetClassifyRepository.findOne(Example.of(assetClassify));
        if (retAssetClassify != null) {
            throw new SczcException(String.format(ASSET_CLASSIFY_IS_EXISTS.getDesc(), model.getName()));
        }

        // 创建新数据
        AssetClassify save = assetClassifyRepository.save(assetClassify);

        BeanUtils.copyProperties(save, model);
        return model;
    }

    @Override
    public List<AssetClassifyModel> findAll() {
        List<AssetClassify> classifyList = assetClassifyRepository.findAll();
        // 将数据转换成model
        List<AssetClassifyModel> modelList = classifyList.stream().map(classify -> {
            AssetClassifyModel classifyModel = new AssetClassifyModel();
            BeanUtils.copyProperties(classify, classifyModel);
            return classifyModel;
        }).collect(Collectors.toList());

        return modelList;
    }
}
